/**
 * 
 */
package com.hand.cloud.b2b.services.impl;

import de.hybris.platform.core.model.order.OrderModel;
import de.hybris.platform.orderprocessing.model.OrderProcessModel;
import de.hybris.platform.processengine.BusinessProcessService;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.store.BaseStoreModel;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hand.cloud.b2b.daos.OrderDAO;
import com.hand.cloud.b2b.services.OrderService;


/**
 * @author StephenWang
 * @time Jul 29, 2014 10:28:38 AM
 * 
 */
@Service(value = "orderService")
public class DefaultOrderService implements OrderService
{

	private static Logger LOG = Logger.getLogger(DefaultOrderService.class);

	@Autowired
	private OrderDAO epOrderDAO;

	@Autowired
	private ModelService modelService;

	@Autowired
	private BusinessProcessService businessProcessService;

	/**
	 * 创建订单
	 * 
	 * @param order
	 * @return
	 */
	@Override
	public OrderModel createOrder()

	{
		//		final OrderModel orderHds = this.orderDao.createOrderHds(order);
		//
		//		for (final AbstractOrderEntryModel entry : order.getEntries())
		//		{
		//			final OrderEntryReceiveModel line = (OrderEntryReceiveModel) entry;
		//
		//			this.orderDao.createOrderEntry(orderHds, line);
		//
		//		}
		//
		//		return orderHds;
		OrderModel order = this.epOrderDAO.createOrder();

		return order;
	}

	/**
	 * 启动订单流程
	 * 
	 * @param orderModel
	 */
	@Override
	public void startProcess(final OrderModel orderModel)
	{
		LOG.info("--------------startProcess------------");
		final OrderModel order = orderModel;
		final BaseStoreModel store = order.getStore();
		final String orderProcessCode = store.getSubmitOrderProcessCode();

		if (orderProcessCode == null || orderProcessCode.isEmpty())
		{
			LOG.error("~~~~~~~~~~~~~~~~~~~~~~>>>>>>>>>>>>>>>>>>>>>Unable to start fulfilment process for order [" + order.getCode()
					+ "]. Store [" + store.getUid() + "] has missing SubmitOrderProcessCode");
		}
		else
		{
			final String processCode = orderProcessCode + order.getCode() + System.currentTimeMillis();
			final OrderProcessModel businessProcessModel = (OrderProcessModel) this.businessProcessService.createProcess(
					processCode, orderProcessCode);

			businessProcessModel.setOrder(order);
			this.modelService.save(businessProcessModel);
			this.businessProcessService.startProcess(businessProcessModel);
		}
	}
}
